package com.greenhouse.business.common.websocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 *
 * @版权 : Copyright (c) 2020 儒安物联技术研发中心
 * @author: 雷扬
 * @E-mail: leiyang@runaiot.com
 * @版本: 1.0
 * @创建日期: 2021年5月8日 下午4:45:37
 * @ClassName GroupWebsocket
 * @类描述-Description: TODO(这里用一句话描述这个方法的作用)
 * @修改记录:
 * @版本: 1.0
 */

@Slf4j
@ServerEndpoint(value = "/ws/group/{groupId}")
@Component
public class GroupWebsocket {
	private static ConcurrentHashMap<String, List<Session>> sessionPools = new ConcurrentHashMap<>();

	private static ConcurrentHashMap<String, Map<String, Object>> groupData = new ConcurrentHashMap<>();

	// 发送消息
	public void sendMessage(Session session, String message) throws IOException {
		if (session != null) {
			synchronized (session) {
				session.getBasicRemote().sendText(message);
			}
		}
	}

	// 给指定用户发送信息
	public void sendInfo(String groupId, String message) {
		JSONObject object = JSONObject.parseObject(message);
		if (!groupData.contains(groupId)) {
			groupData.put(groupId, new HashMap<String, Object>());
		}
		groupData.get(groupId).putAll(object.getInnerMap());

		log.info("发送消息：" + message);
		if (!sessionPools.containsKey(groupId)) {
			return;
		}

		sessionPools.get(groupId).forEach(session -> {
			try {
				sendMessage(session, JSONObject.toJSONString(groupData.get(groupId)));
			} catch (Exception e) {
				e.printStackTrace();
			}
		});

	}

	// 建立连接成功调用
	@OnOpen
	public void onOpen(Session session, @PathParam(value = "groupId") String groupId) {

		if (sessionPools.get(groupId) == null) {
			sessionPools.put(groupId, new ArrayList<>());
		}

		sessionPools.get(groupId).add(session);

		if (groupData.containsKey(groupId)) {
			try {
				sendMessage(session, JSONObject.toJSONString(groupData.get(groupId)));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// 关闭连接时调用
	@OnClose
	public void onClose(Session session) {
		if (sessionPools.size() == 0) {
			return;
		}
		sessionPools.values().forEach(sessions -> {
//			for (Session sessionn : sessions) {
//				if (sessionn.getId().equals(session.getId())) {
//					sessions.remove(sessionn);
//				}
//			}
			sessions.remove(session);
		});

	}

	// 收到客户端信息
	@OnMessage
	public void onMessage(String message) throws IOException {
		message = "客户端：" + message + ",已收到";
		log.info(message);
	}

	// 错误时调用
	@OnError
	public void onError(Session session, Throwable throwable) {
		log.error("发生错误", throwable);
	}
}
